import React from 'react';
import {
    View,
    Text,
    FlatList,
    TouchableOpacity,
    Dimensions,
    Image, TextInput,
} from 'react-native';
import styles from './styles';
import NavigationBar from '../../common/NavigationBar';
import {BASE_URL} from '../../common/BASE_URL';
import HttpUtils from '../../expand/dao/HttpUtils';
import {Constant, StylesConstant} from '../../common/Constant';
import StorageUtil from '../../utils/StorageUtil';
import NavigationUtil from '../../navigators/NavigationUtil';
import Utils from '../../utils/Utils';
import GlobalStyles from '../../common/styles/GlobalStyles';
import {Tabs} from '@ant-design/react-native';
import ToastUtil from '../../utils/ToastUtil';
import RegulationItem from './components/RegulationItem';
import FontAwesome from "react-native-vector-icons/FontAwesome";

let current = 0;
let total = 0;
const size = 10;
// 待办案件
const getRegulationsUrl = BASE_URL.apiBaseUrl + '/app/regulations'
// 待办事件
const getRightMattersUrl = BASE_URL.apiBaseUrl + '/app/rightsMatters'

export default class Regulations extends React.Component {
    constructor(props) {
        super(props);
        // 获取参数
        let tabIndex = 0;
        this.state = {
            tabIndex: tabIndex,
            isLoading: false, // list加载状态
            hideLoadingMore: false,
            caseList: [{id:1},{id:2}],
            dataList2: [],
            dealtCaseList: [],
            query: {
                // current: 1, // 当前页数
                // size: 10, // 每页大小
                queryStr: '', // 模糊查询
                matterName: null,
                regulationsName: null,
            },
        };
    }

    componentDidMount() {
        this.loadData();
    }

    loadData(loadMore) {
        const {tabIndex} = this.state;
        if(this.state.isLoading) return
        let url = ''
        let params = {size: size, page: current}
        if(tabIndex === 1) {
            params = {size: size, page: current}
            url = getRightMattersUrl
        }else if(tabIndex === 0) {
            params = {size: size, page: current}
            url = getRegulationsUrl
        }
        if(url){
            // this.state.isLoading = true
            const bool = this.isLoadMore(loadMore); // 4.的判断是否需要加载更多
            if(bool){
                // const key = ToastUtil.loading('加载中...')
                HttpUtils.request({
                    url: url,
                    params
                }).then(res=>{
                    // console.log(res)
                    // ToastUtil.remove(key)
                    const {content, totalElements} = res
                    const data = {
                        dealtCaseList: loadMore
                            ? this.state.dealtCaseList.concat(content)
                            : content,
                    }
                    // 如果当前查询的是最后一页，则更新FlatList底部控制器的文字，显示没有更多数据
                    const totalPage = parseInt(((totalElements-1)/size))
                    total = totalPage;
                    if (current == totalPage) {
                        data.hideLoadingMore = true;
                    }
                    // 如果当前查询的是第一页，但是没有查出数据，给出提示，并修改底部文字
                    if (current == 0 && content.length === 0) {
                        data.hideLoadingMore = true;
                        ToastUtil.info('没找到相关数据');
                    }
                    this.setState({
                        isLoading: false,
                        ...data
                    })
                }).catch(e=>{
                    // ToastUtil.remove(key)
                    // console.log(e);
                    this.setState({
                        isLoading: false
                    })
                })
            }
        }

    }
    // 初始化数据
    async initDriverList() {
        const code = await StorageUtil.get(Constant.companyCode);
        if (code) {
            this.setState({
                isLoading: true,
            });
            HttpUtils.request({
                // url: URL,
                type: 'post',
                data: {companyCode: code, type: this.state.type},
            })
                .then((result) => {
                    const data = result.data;
                    this.setState({
                        caseList: data,
                        isLoading: false,
                    });
                })
                .catch((_) => {
                    this.setState({
                        isLoading: false,
                    });
                });
        }
    }

    _renderHeaderBtn(){
        return (
            this.state.tabIndex=== 3?
            <View style={{flexDirection: 'row'}}>
                <Image source={require('../../assets/images/item/icon_sign.png')} style={{width: 18,height: 18,marginRight: 5}} />
                <Text style={{color: '#4D70CC'}}>批量签名</Text>
            </View>: null
        )
    }
    render() {
        const {navigation} = this.props;
        const {tabIndex} = this.state;
        return (
            <View style={GlobalStyles.pageContainer}>
                {/* 自定义顶部导航条 */}
                <NavigationBar
                    navigation={navigation}
                    headerBackTitle={'法规清单'}
                    headerRightButtons={[
                        this._renderHeaderBtn()
                    ]}
                />
                <View style={{flex: 1}}>
                    <Tabs
                        style={[styles.container, GlobalStyles.bgGrey]}
                        initialPage={tabIndex}
                        tabBarTextStyle={GlobalStyles.tabsTextStyle}
                        tabBarUnderlineStyle={GlobalStyles.tabsLineStyle}
                        tabBarActiveTextColor={GlobalStyles.tabBarActiveTextColor}
                        tabBarInactiveTextColor={GlobalStyles.tabBarInactiveTextColor}
                        onChange={(tab, index) => this.handleTabChange(tab, index)}
                        tabs={[
                            {title: '法规条款'},
                            {title: '权利事项'},
                        ]}>
                        <View tabLabel="法规条款">
                            <View style={{backgroundColor: '#fff',borderTopWidth: 1,borderColor: '#eee'}}>
                                {this._renderRegulationSearch()}
                            </View>
                            {this._renderRegulationList()}
                        </View>
                        <View tabLabel="权利事项">
                            <View style={{backgroundColor: '#fff',borderTopWidth: 1,borderColor: '#eee'}}>
                                {this._renderMatterSearch()}
                            </View>
                            {this._renderRegulationList()}
                        </View>
                    </Tabs>
                </View>
            </View>
        );
    }
    _renderMatterSearch(){
        return (
            <View style={[GlobalStyles.searchInputContainer,{paddingLeft: 10}]}>
                <TextInput
                    style={[GlobalStyles.searchIpt]}
                    ref="input"
                    multiline={false}
                    placeholder={'请输入关键字检索'}
                    onChangeText={(text) => {
                        this.setState({
                            query: {
                                ...this.state.query,
                                matterName: text
                            },
                        });
                    }}
                />
                <TouchableOpacity
                    style={{flex: 1,marginRight: 5,alignItems: 'center'}}

                >
                    <View style={{flexDirection: 'row',alignItems: 'center'}}>
                        <FontAwesome name={'search'} size={16} color={StylesConstant.themeIconColor}/>
                        <Text style={{color: StylesConstant.themeIconColor,fontSize: 14,paddingLeft: 5}}
                        >检索</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }
    _renderRegulationSearch(){
        return (
            <View style={[GlobalStyles.searchInputContainer,{paddingLeft: 10}]}>
                <TextInput
                    style={[GlobalStyles.searchIpt]}
                    ref="input"
                    multiline={false}
                    placeholder={'请输入关键字检索'}
                    onChangeText={(text) => {
                        this.setState({
                            query: {
                                ...this.state.query,
                                regulationsName: text
                            },
                        });
                    }}
                />
                <TouchableOpacity
                    style={{flex: 1,marginRight: 5,alignItems: 'center'}}

                >
                    <View style={{flexDirection: 'row',alignItems: 'center'}}>
                        <FontAwesome name={'search'} size={16} color={StylesConstant.themeIconColor}/>
                        <Text style={{color: StylesConstant.themeIconColor,fontSize: 14,paddingLeft: 5}}>检索</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }
    _renderRegulationList() {
        const {dealtCaseList, isLoading} = this.state;
        return (
            <FlatList
                style={styles.list}
                data={dealtCaseList}
                keyExtractor={(item, index) => `case_dealt_${index}`}
                renderItem={(data) => this._renderRegulationItem(data)}
                refreshControl={Utils.renderRefreshControl('加载中', isLoading, () => {
                    this.loadData();
                })}
                ListFooterComponent={() => this.genIndicator()}
                onEndReached={() => {
                    setTimeout(() => {
                        if (this.canLoadMore) {
                            this.loadData(true);
                            this.canLoadMore = false;
                        }
                    }, 100);
                }}
                onEndReachedThreshold={0.5}
                onMomentumScrollBegin={() => {
                    this.canLoadMore = true;
                }}
            />
        )
    }
    handleTabChange(obj, index) {
        if (this.state.index !== index) {
            this.state.tabIndex = index;
            this.state.dealtCaseList = []
            this.loadData();
        }
    }
    _renderRegulationItem(data){
        const {item} = data;
        const {tabIndex} = this.state
        return (
            <RegulationItem
                item={item}

                handleCallback={() => {
                    if(tabIndex == 0){
                        NavigationUtil.goPage('TextDetail', {
                            detail: item.regulationsContent
                        });
                    }else if(tabIndex == 1) {
                        // NavigationUtil.goPage('CaseReport', {
                        //     caseCode: item.caseCode,
                        //     matterId: item.id,
                        //     linkId:item.linkId,
                        //     type: 'inspection'
                        // });
                    }
                }}
            />
        );
    }

    genIndicator() {
        const {hideLoadingMore} = this.state;
        return hideLoadingMore
            ? Utils.renderNoDataBottom()
            : Utils.renderLoadingMore();
    }

    getListBottom(isLoading, data) {
        return !isLoading && data && data.length === 0
            ? Utils.renderNoDataBottom()
            : null;
    }

    isLoadMore(loadMore) {
        // 如果触发了加载更多，但是当前页数 === 总页数，做出提示，终止该函数运行
        if (loadMore && current == total) {
            ToastUtil.info('没有更多了'); // 弹框提示
            // 修改FlatList控制器的底部显示
            this.setState({
                hideLoadingMore: true,
            });
            return false;
        }
        // 如果需要加载更多，自动翻页
        if (loadMore) {
            current++;
        } else {
            // 反之表示数据初始化，当前页重设为第一页，并修改FlatList底部控制器的文字，显示为正在加载...
            current = 0;
            this.setState({
                hideLoadingMore: false,
            });
        }
        return true;
    }

}
